<?php
defined('IN_YZMPHP') or exit('Access Denied');
yzm_base::load_controller('common', 'admin', 0);
yzm_base::load_model("menu_model", "admin");

class index extends common
{

    public function __construct()
    {
        parent::__construct();
    }

    public function init()
    {
        $adminid = intval(get_cookie('admin_id'));
        include $this->admin_tpl('index');
    }

    public function public_welcome()
    {
        include $this->admin_tpl('welcome');
    }

    /**
     * 获取后台菜单
     * @return void
     */
    public function menu()
    {
        $adminId   = cmf_get_admin_id();
        $menuModel = new menu_model();
        if (getcache('cacheAdminMenuId'.$adminId)) {
            $menuInfo = getcache('cacheAdminMenuId'.$adminId);
        } else {
            $menuInfo = $menuModel->getMenuTree();
            setcache('cacheAdminMenuId'.$adminId, $menuInfo);
        }
        $data = ['code' => 1, 'data' => $menuInfo, 'msg' => 'ok'];

        return_json($data);
    }

    /**
     * 登录
     * @return void
     */
    public function login()
    {
        if (is_post()) {
            $param = input("post.");
            if (empty($param['username']) || empty($param['password'])) {
                return_error("用户名或密码不能为空");
            }
            if ( ! is_password($param['password'])) {
                return_error("密码长度不符合");
            }
            if ($param['code'] != $_SESSION['captcha_code']) {
                return_error("验证码不正确");
            }
            $check = $this->check_login_admin(remove_xss(trim($param['username'])),
                remove_xss(trim($param['password'])));

            return_json($check);
        }
        $this->beforeAction();
        include $this->admin_tpl('login');
    }

    /**
     * 登录页前置调用方法，判断是否已登录
     * @return void
     */
    public function beforeAction()
    {
        $adminId = cmf_get_admin_id();
        if ( ! empty($adminId)) {
            showmsg("您已登录，无需再次登录", U("admin/index/init"));
        }
    }

    /**
     * 注销登录
     */
    public function login_out()
    {
        clear_session();
        return_success("退出登录成功");
    }

    /**
     * 清除缓存
     */
    public function cacheClear()
    {
        $adminId = cmf_get_admin_id();
        delcache('cacheAdminMenuId'.$adminId);
        delcache('cache_auth_rules');

        $runTimeArr    = C('runtime_dir');
        $runTimePath   = YZMPHP_PATH.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
        $run_time_path = scandir($runTimePath);
        foreach ($run_time_path as $val) {
            if ( ! in_array($val, $runTimeArr)) {
                continue;
            }
            if ( ! is_dir($runTimePath.$val)) {
                continue;
            }
            $dir = $runTimePath.$val.'/';
            //先删除目录下的文件：
            $dh = opendir($dir);
            while ($file = readdir($dh)) {
                if ($file != "." && $file != "..") {
                    $fullPath = $dir.$file;
                    if ( ! is_dir($fullPath)) {
                        @unlink($fullPath);
                    } else {
                        dir_delete($fullPath);
                    }
                }
            }
            closedir($dh);
            @rmdir($runTimePath.$val.'/');
        }
        return_success('清除缓存成功');
    }

    /**
     * 上传图片多选框
     */
    public function file_list()
    {
        $type       = input('get.type', 'many');
        $select_id  = input('get.select_id');
        $group_list = D('upload_group')->select();
        $total_pics = D('upload_file')->where(['is_delete' => 0])->total();

        include $this->admin_tpl('file_list');
    }

    public function check_login_admin($username, $password)
    {
        $admin           = D('admin');
        $admin_login_log = D('admin_login_log');
        $res             = $admin->where(['username' => $username])->find();
        if (empty($res)) {
            $this->insertLoginLog($username, $password, 0, "登录失败！");

            return ['error' => 0, 'msg' => '账号或密码错误！'];
        }
        // 限制密码连续错误次数
        if ($res['err_num'] >= 5) {
            $limit_arr  = array(
                5  => 300,
                8  => 600,
                12 => 1800,
            );
            $limit_time = isset($limit_arr[$res['err_num']]) ? $limit_arr[$res['err_num']] : 0;
            if ($limit_time) {
                $last_time = $admin_login_log->field('login_time')->where([
                    'username'     => $username,
                    'login_result' => 0
                ])->order('id DESC')->one();
                if (time() - $last_time < $limit_time) {
                    return [
                        'code' => 0,
                        'msg'  => "登录错误次数过多，请".ceil(($last_time + $limit_time - SYS_TIME) / 60)."分钟之后再试"
                    ];
                }
            }
        }

        //判断用户名密码是否正确
        if (cmf_password($password, $res['salt']) != $res['password']) {
            $this->insertLoginLog($username, $password, 0, "登录失败！");
            $admin->update("err_num=err_num+1", ['id' => $res['id']]);

            return ['error' => 0, 'msg' => '账号或密码错误！!'];
        }
        //判断是否禁用
        if ( ! $res['status']) {
            $this->insertLoginLog($username, $password, 0, "账户被禁用！");

            return ['error' => 0, 'msg' => '该账户已被禁用！'];
        }
        $this->insertLoginLog($username, "******", 1, "登录成功！");
        $admin->update(['err_num' => 0, 'update_time' => time(), 'login_time' => time(), 'login_ip' => getip()],
            ['id' => $res['id']]);

        //写入缓存
        set_cookie("admin_id", $res['id']);
        set_cookie("cookie_admin", $res);
        set_session('admin_id', $res['id']);
        set_session('admin_name', $res['username']);
        set_session('session_admin', $res);
        set_session('role_id', $res['role_id']);

        return ['code' => 1, 'msg' => '登录成功'];
    }

    //写入登录日志
    private function insertLoginLog($username, $password, $login_result, $cause = '')
    {
        $admin_log = get_config('admin_log');
        if ( ! $admin_log) {
            return;
        }
        $loginLog = D('admin_login_log');
        $data     = [
            'username'     => $username,
            'password'     => $password,
            'login_time'   => time(),
            'login_ip'     => getip(),
            'login_result' => $login_result,
            'cause'        => $cause,
            'create_time'  => time(),
            'update_time'  => time()
        ];
        $loginLog->insert($data);
    }

}
